package mt.demo.web.controllerAspect;

import mt.demo.service.comm.WatControllerDefaultData;
import mt.demo.service.security.WatUserDetails;
import mt.demo.web.comm.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by watson on 2015/12/2.
 */
@Component
public class CsrfShareDataAspect {
    @Autowired
    private R r;
    @Autowired
    private WatControllerDefaultData defaultData;


    /**
     * 重构ModelAndView
     *
     * @param modelAndView
     */
    public void refactorModelAndView(ModelAndView modelAndView) {
        if (modelAndView == null) {
            modelAndView = new ModelAndView();
        }
        modelAndView.addObject("nickname", getNickname());
        modelAndView.addObject("r", r);
    }

    /**
     * 设置token
     * @param request
     */
    //获取csrfkoen
    public void addData(ModelAndView mav, HttpServletRequest request) {
        if(mav != null){
            getCsrfToken(mav.getModelMap(), request);
        }
    }
    //获取csrfkoen
    private void getCsrfToken(ModelMap modelMap, HttpServletRequest request){
        CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
        if (csrfToken != null) {
            modelMap.addAttribute("_csrf", csrfToken);
        }
    }
    /**
     * 获取用户昵称
     *
     * @return
     */
    private String getNickname() {
        WatUserDetails details = defaultData.getCurrentYomsUserDetails();
        if (details != null) {
            return details.getNickname();
        }
        return "NULL";
    }

}
